/**
 * Created by ss on 16/4/10.
 */
var $ = require('jquery');
var init = require('../util/init.js');
var util = require('../util/util.js');
var templateUtil = require('../util/templateUtil.js');
var addSendTpl = require('../../tpl/addSend.tpl');
require('../../scss/addSend.scss');

init.initNav(true, '添加发件');
var initData = {
    address: "",
    latitude: "",
    longitude: "",
    name: "",
    phone: ""
};
var receiver = localStorage.getItem("receiver")? JSON.parse(localStorage.getItem("receiver")) : $.extend({},initData);
var sender = localStorage.getItem("sender")? JSON.parse(localStorage.getItem("sender")) : $.extend({},initData);
var initObject = {
    receiver: receiver,
    sender: sender,
    type: localStorage.getItem("type") || 0
};
initValue(initObject);
function initValue(data){
    if(!data.sender.phone){
        data.sender.phone = util.getUserStore();
    }
    $("#contentContainer").html(templateUtil.template(addSendTpl, {data: data}));
}
$(".address").click(function () {
    var parent = $($(this).parents('.nameInput'));
    var url = "./mapSearch?type=" + parent.attr("id");
    var address = $(this).find("input[name='address']").val();
    if(address) {
        url += "&value=" + encodeURIComponent(address) + "&latitude=" + initObject[parent.attr("id")].latitude + "&longitude=" + initObject[parent.attr("id")].longitude;
    }
    flush();
    util.changePage(url);
});

$("input[name='name']").on('input', function () {
    var parent = $($(this).parents('.nameInput'));
    initObject[parent.attr("id")].name = $(this).val();
});

$("input[name='phone']").on('input', function () {
    var parent = $($(this).parents('.nameInput'));
    initObject[parent.attr("id")].phone = $(this).val();
});

$(".chooseType .item").click(function () {
    $(".chooseType .item").removeClass("on");
    $(this).addClass("on");
    initObject.type = $(this).attr("data-type");
});

$(".button").click(function () {
    flush();
    if(!initObject.receiver.phone){
        alert("收件人的电话不能为空哦");
        return false;
    }
    if(!initObject.sender.phone){
        alert("寄件人的电话不能为空哦");
        return false;
    }
    if(!initObject.receiver.address){
        alert("收件人的地址不能为空哦");
        return false;
    }
    if(!initObject.sender.address){
        alert("寄件人的地址不能为空哦");
        return false;
    }
    if(!initObject.receiver.name){
        alert("收件人的姓名不能为空哦");
        return false;
    }
    if(!initObject.sender.name){
        alert("寄件人的姓名不能为空哦");
        return false;
    }
    util.changePage("./chooseSendType");
});

function flush(){
    localStorage.setItem('receiver', JSON.stringify(initObject.receiver));
    localStorage.setItem('sender', JSON.stringify(initObject.sender));
    localStorage.setItem('type', initObject.type);
}

window.onunload = flush;
